import NewsApi from '@/api/news'
import { useCancelToken } from '@/utils/request'


const state = {
  uploadList: [], // 媒体中心 媒体上传列表
  singleUploading: false, // 正在逐个上传
  isQuikUpload:false,
}

function copyState () {
  console.log('copyState------', state)
  return JSON.parse(JSON.stringify(state))
}

const mutations = {
  SET_UPLOAD_LIST: (state, fileList) => {
    state.uploadList = fileList.map(file => {
      const _file = {
        ...file
      }
      if (!file.file_status && file.file_status !== 0) _file.file_status = 'wating'
      if (!file.speed) _file.speed = ''
      if (!file.file_overTime) _file.file_overTime = ''
      return _file
    })
  },
  SET_SINGLE_UPLOADING: (state, isUploading) => {
    state.singleUploading = isUploading
  },
  UPDATE_UPLOAD_LIST_FILE: (state, { file, props }) => {
    const _file = state.uploadList.find(f => f.uid === file.uid)
    if (!_file) return false
    for (const prop in props) {
      _file[prop] = props[prop]
    }
  },
  DELETE_UPLOAD_LIST_FILE: (state, { file }) => {
    const _fileIndex = state.uploadList.findIndex(f => f.uid === file.uid)
    if (_fileIndex < 0) return false
    const _file = state.uploadList[_fileIndex]
    const {file_status, cancelControl} = _file
    if (typeof file_status === 'number') {
      cancelControl && cancelControl.cancel()
    }
    state.uploadList.splice(_fileIndex, 1)
  },
  DELETE_UPLOAD_LIST_BY_FILESTATUS: (state, file_status) => {
    switch (file_status) {
      case 'fail':
      case 'success':
        state.uploadList = state.uploadList.filter(file => {
          const needRemove = file.file_status === file_status
          return !needRemove
        })
        break;
      default: // 默认删除所有的
        state.uploadList.forEach(file => {
          if (typeof file.file_status === 'number') { // 如果正在上传需要中断上传请求
            file.cancelControl && file.cancelControl.cancel()
          }
        });
        state.uploadList = []
        break;
    }
  },
  CHANGE_QUIKUPLOAD: (state, { key, value }) => {
    // eslint-disable-next-line no-prototype-builtins
    if (state.hasOwnProperty(key)) {
      state[key] = value
    }
  },
}

const actions = {
  setUploadList({ commit }, fileList) {
    commit('SET_UPLOAD_LIST', fileList)
  },
  singleUpload({ state, dispatch, commit }) {
    const fetchingNum = state.uploadList.filter(item => {
      return typeof item.file_status === 'number'
    }).length
    if (fetchingNum > 0) return // 有上传中的文件
    const file = state.uploadList.find(item => item.file_status === 'wating')
    if (!file) return commit('SET_SINGLE_UPLOADING', false)// 已没有等待上传的文件

    commit('SET_SINGLE_UPLOADING', true)
    dispatch('uploadFetch', {file, finalCb: () => {
      dispatch('singleUpload')
    }})
  },
  async uploadFetch({ commit }, {file, finalCb}) {
    const [cancelToken, cancelControl] = useCancelToken()
    const _file = file
    commit('UPDATE_UPLOAD_LIST_FILE', {file: _file, props: {cancelControl}})
    try {
      let params = {
        file: _file.raw,
        folderId: typeof _file.menu === 'string' ? Number(_file.menu) : 0, // typeof _file.menu === 'string' ? 0 : _file.menu,
        convert: _file.isConvert
      }
      if (_file.ownerUserId) params.ownerUserId = _file.ownerUserId
      const res = await NewsApi.upload(params, (p, s, over) => {
        commit('UPDATE_UPLOAD_LIST_FILE', {
          file: _file,
          props: {
            file_status: p,
            speed: s,
            file_overTime: over
          }
        })
      }, cancelToken)

      commit('UPDATE_UPLOAD_LIST_FILE', {
        file: _file,
        props: {
          file_status: !res ? 'fail' : 'success'
        }
      })
    } catch (error) {
      
      commit('UPDATE_UPLOAD_LIST_FILE', {
        file: _file,
        props: {
          file_status: 'fail'
        }
      })
      
    } finally {
      
      commit('UPDATE_UPLOAD_LIST_FILE', {
        file: _file,
        props: {
          speed: '',
          file_overTime: ''
        }
      })
      finalCb && finalCb()
     
    }
  },
  delUpload({commit}, {file, fileState}) {
    if (file) {
      commit('DELETE_UPLOAD_LIST_FILE', {file})
    } else {
      commit('DELETE_UPLOAD_LIST_BY_FILESTATUS', fileState)
    }
  },
  changeQuikUpload({ commit }, data) {
    commit('CHANGE_QUIKUPLOAD', data)
  },
}

const getters = {
  
}

export default {
  namespaced: true,
  state: copyState(),
  mutations,
  actions,
  getters
}
